package twitter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Trends {

    public enum TrendType {
        WEEKLY("weekly"),
        CURRENT("current"),
        DAILY("daily");

        String part;

        TrendType(String part) {
            this.part = part;
        }

        public String getPart() {
            return part;
        }
    }


    private static String PART_TRENDS = "trends/";

    private final URI uri;

    public Trends(TrendType trend) {
        uri = TwitterUri.createApiUri(PART_TRENDS + trend.getPart());
    }

    private JSONObject trendsObject;

    public void build() {
        trendsObject = NetUtil.downloadUrl(uri);
    }


    public Set<String> getQueries() {

        try {
            JSONObject trendsByTime = trendsObject.getJSONObject("trends");
            Set<String> queries = new HashSet<String>();
            for (Iterator iterator = trendsByTime.keys(); iterator.hasNext();) {
                JSONArray jsonArray = trendsByTime.getJSONArray(iterator.next().toString());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject trend = jsonArray.getJSONObject(i);
                    queries.add(trend.getString("query"));
                }
            }
            return queries;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }


    public Set<String> getTweetTexts() {
        Set<String> texts = new HashSet<String>();
        Set<String> queries = getQueries();
        Search.Builder builder = new Search.Builder();
        builder.setRpp(100).setType("recent");
        for (String query : queries) {
            builder.setQuery(query);
            for (int page = 1; page <= 15; page++) {
                builder.setPage(page);
                for (Tweet tweet : builder.build().getResult()) {
                    texts.add(tweet.getText());
                }
            }
        }
        return texts;
    }

}
